const Base = require('../../base.js');

module.exports = class extends Base {
  async indexAction() {
    let admin_login = await this.session('admin_login')
    if (!admin_login) {
      return this.fail(-1, '未授權的訪問')
    }
    let data = this.post()
    /// 获取任务回复
    const task_result_db = this.mongoose('mongo/task_result')
    let task_result = await task_result_db.findOne(think.objId(data._id))
    /// 获取关联用户
    const users_db = this.mongoose('mongo/users')
    let users = await users_db.findOne(think.objId(task_result.uid))
    /// 获取关联任务
    const task_db = this.mongoose('mongo/task')
    let task = await task_db.findOne(think.objId(task_result.tid))

    if (task_result.status != 1) return this.fail(-1, '已经审核过了，不要重复审核')

    /// 拒绝任务
    if (data.status == -1) {
      await task_result_db.updateOne({ _id: think.objId(data._id) }, {
        status: -1,
        update_at: Date.now(),
      })
      return this.json({
        status: 200, message: 'success', data: data.status
      })
    }
    /// 通过审核
    await task_result_db.updateOne({ _id: think.objId(data._id) }, {
      status: 2,
      update_at: Date.now(),
    })
    let money = task.reward * (task.commission / 100)
    let toPid = 0
    /// 如果有上级用户还需要给上级
    if (users.pid) {
      toPid = money * (task.rebate / 100)
      await this.model('deal/index').add({
        type: 'deduct',
        uid: users.pid,
        tip: task_result.tid,
        money: toPid,
        status: 1
      })
      money = money - toPid
    }
    /// 生成交易订单
    await this.model('deal/index').add({
      type: 'commission',
      uid: task_result.uid,
      tip: task_result.tid,
      money: money,
      status: 1
    })
    /// 返回结果
    this.json({
      status: 200,
      message: 'success', data: data.status
    })
  }
};
